const router = require('koa-router')()

router
.post('/login', async (ctx, next) => {
  ctx.body =  '登录'
})
.post('/register', async (ctx, next) => {
  ctx.body =  '注册'
})


// 获取文章推荐
.post('/getArticles', async (ctx, next) => {
  let query = ctx.request.body
  try {
    let result = await ctx.db.Articles.find({
      ...query
    }, '-articleContent')
    .populate('articleType')
    .sort({ updateTime: 'desc'})
    ctx.body = {
      code: 0,
      message: '查询成功',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取关于文章
.get('/getAboutArticle', async (ctx, next) => {
  try {
    let result = await ctx.db.Articles.findOne({
      articleTitle:'关于'
    })
    .populate('articleType')
    .sort({ updateTime: 'desc'})
    ctx.body = {
      code: 0,
      message: '关于文章查询成功',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取文章列表 ↓
.post('/getArticleList', async (ctx, next) => {

  /*
    入参
    title: String,
    type: id,
    pageSize: Number,
    currentPage: Number,
  */
  let query = ctx.request.body
  console.log('得到文章列表', query)

  // 设置查询对象
  let selectOption = {}
  if(!!query.type) selectOption['articleType'] = query.type
  if(!!query.title) selectOption['articleTitle'] =  {$regex: query.title}

  try {
    const product = await ctx.db.Articles.find({
      ...selectOption
    })
    .populate('articleType')
    .sort('-createTime')
    .skip((query.currentPage-1) * query.pageSize)
    .limit(query.pageSize)
    .exec()

    let counts = await ctx.db.Articles.find({
      ...selectOption
    }).countDocuments().exec()

    ctx.body = {
      code: 0,
      message: '获取文章列表成功',
      data: {
        articleList: product,
        counts: counts
      }
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = {
      code: 1,
      message: error.message,
      data: null
    }
  }
})

// 获取最新文章
.get('/getNewArticles', async (ctx, next) => {
  try {
    let result = await ctx.db.Articles.find({}, '-articleContent')
    .populate('articleType')
    .sort({createTime: 'desc'})
    .limit(10)
    ctx.body = {
      code: 0,
      message: '成功查询最新10篇文章',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取文章详情
.get('/getArticleDeteil', async (ctx, next) => {
  console.log(ctx.query)
  let id = ctx.query.id
  try {
    
    let result = await ctx.db.Articles.findOne({_id: id})
    .populate('articleType')
    let commentsNum = await ctx.db.ArticleComments.find({
      commentArticleId: id
    }).countDocuments().exec()
    ctx.body = {
      code: 0,
      message: '查询文章详情成功',
      data: result
    }
    // 只要获取文章的详情，酒吧点赞数加 1
    // 更新数量在返回文章数据之后，因为并不需要返回数据
    let looknum = await ctx.db.Articles.findById(id, 'looknum')
    let addOne = looknum.looknum + 1
    await ctx.db.Articles.updateOne({_id: id},{
      'looknum': addOne
    })

  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 文章点赞
.get('/giveALike', async (ctx, next) => {
  console.log(ctx.query)
  let id = ctx.query.id
  try {
    let likenum = await ctx.db.Articles.findById(id, 'likenum')
    let addOne = likenum.likenum + 1
    let result = await ctx.db.Articles.updateOne({_id: id},{
      'likenum': addOne
    })
    ctx.body = {
      code: 0,
      message: '成功查询最新10篇文章',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 添加留言
.post('/addGuest', async (ctx, next) => {
  let query = ctx.request.body
  console.log(query)
  try {
    let result = await ctx.db.GuestBook.create({
      ...query,
      createTime: new Date()
    })
    ctx.body = {
      code: 0,
      message: '添加留言成功',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取留言列表
.post('/getGuestList', async (ctx, next) => {
  let {pageSize, currentPage} = ctx.request.body
  try {
    let result = await ctx.db.GuestBook.find()
    .skip((currentPage-1) * pageSize)
    .limit(pageSize)
    .sort('-createTime')

    let counts = await ctx.db.GuestBook.find().countDocuments().exec()

    ctx.body = {
      code: 0,
      message: '获取留言成功',
      data: {
        guestList: result,
        counts: counts
      } 
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取文章类型列表 ↓
.get('/getArticleTypeList', async (ctx, next) => {
  let articleTypesList
  try {
    articleTypesList = await ctx.db.ArticleTypes.find()
    ctx.body = {
      code: 0,
      message: '获取文章类型列表成功',
      data: articleTypesList
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 0, message: error.message, data: null}
  }
})

// 添加文章评论
.post('/addComment', async (ctx, next) => {
  let query = ctx.request.body
  console.log('添加文章评论', query)
  try {
    let result = await ctx.db.ArticleComments.create({
      ...query,
      'createTime': new Date()
    })
    ctx.body = {
      code: 0,
      message: '添加留言成功',
      data: result
    }
    let commentNum = await ctx.db.ArticleComments.find({
      commentArticleId: query.commentArticleId
    }).countDocuments().exec()
    ctx.db.Articles.updateOne({
      _id: query.commentArticleId
    }, {
      'commentNum': commentNum 
    }).then(res => {
      console.log('修改评论数成功', res)
    })
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取文章评论列表
.post('/getCommentList', async (ctx, next) => {
  let query = ctx.request.body
  console.log('获取文章评论', query)
  try {
    let result = await ctx.db.ArticleComments.find({
      commentArticleId: query.commentArticleId
    })
    .skip((query.currentPage-1) * query.pageSize)
    .limit(query.pageSize)
    .sort('-createTime')

    let commentNum = await ctx.db.ArticleComments.find({
      commentArticleId: query.commentArticleId
    }).countDocuments().exec()

    ctx.body = {
      code: 0,
      message: '获取留言成功',
      data: {
        commentList: result,
        counts: commentNum
      } 
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 获取文章列表 ↓
.post('/searchArticle', async (ctx, next) => {

  /*
    入参
    title: String,
    pageSize: Number,
    currentPage: Number,
  */
  let query = ctx.request.body
  console.log(query)

  // 设置查询对象
  let selectOption = {}
  if(!!query.title) selectOption['articleTitle'] =  {$regex: query.title}

  try {

    const product = await ctx.db.Articles.find({
      ...selectOption
    })
    .populate('articleType')
    .sort('-createTime')
    .skip((query.currentPage-1) * query.pageSize)
    .limit(query.pageSize)
    .exec()

    let counts = await ctx.db.Articles.find({
      ...selectOption
    }).countDocuments().exec()

    ctx.body = {
      code: 0,
      message: '获取文章列表成功',
      data: {
        articleList: product,
        counts: counts
      }
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = {
      code: 1,
      message: error.message,
      data: null
    }
  }
})

module.exports = router